package com.urbanski.clipboard.server.action.message;

import java.io.IOException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.common.message.JoinMessage;
import com.urbanski.clipboard.common.message.JoinResponse;
import com.urbanski.clipboard.common.message.Message;
import com.urbanski.clipboard.common.message.JoinResponse.JoinResponseValue;
import com.urbanski.clipboard.server.ClientSocket;
import com.urbanski.clipboard.server.ClipboardServer;
import com.urbanski.clipboard.server.session.ServerSession;
import com.urbanski.util.logging.LoggingUtil;

public class JoinMessageHandler extends ServerMessageHandler
{
	private static final Logger LOGGER = Logger.getLogger(JoinMessageHandler.class);

	public JoinMessageHandler(ClientSocket client)
	{
		super(client);
	}

	@Override
	public void handle(Message message)
	{
		JoinMessage joinMessage = (JoinMessage)message;

		ServerSession session = ClipboardServer.getSession(joinMessage.getSessionName());
		JoinResponse response;

		if (session == null)
		{
			response = new JoinResponse(JoinResponseValue.SESSION_DOES_NOT_EXIST);
		}
		else if (session.getSessionPassword() != null && !session.getSessionPassword().equals(joinMessage.getSessionPassword()))
		{
			response = new JoinResponse(JoinResponseValue.INVALID_PASSWORD);
		}
		else if (session.getClients().get(client.getClientName()) != null)
		{
			response = new JoinResponse(JoinResponseValue.ALREADY_MEMBER);
		}
		else
		{
			session.addClient(client);
			response = new JoinResponse(JoinResponseValue.SUCCESS);
		}
		
		System.out.println("Session join response: " + response.getResponseText());

		try
		{
			client.sendResponse(response);
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error sending response", e);
		}
	}

}
